package com.itcoon.cloud.framework.validation.config;
/**
 * @author Athric Yu
 * 2024/11/27
 **/

import com.itcoon.cloud.framework.i18n.I18ns;
import com.itcoon.cloud.framework.i18n.config.I18nConfiguration;
import com.itcoon.cloud.framework.utils.SpringUtils;
import com.itcoon.cloud.framework.validation.config.properties.ValidationProperties;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.MessageSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

/**
 *
 *
 * @author Athric Yu
 * 2024/11/27
 **/
@EnableConfigurationProperties(ValidationProperties.class)
@AutoConfigureAfter({SpringUtils.class, I18nConfiguration.class})
@AutoConfiguration
public class ValidationConfig {

    public ValidationConfig(ValidationProperties properties) {
        Validator validator = initValidator(I18ns.getInstance(properties.getMessageSourceRegisterKey()).getMessageSource());
        SpringUtils.registerSingleton("initValidator", validator);
    }


    public Validator initValidator(MessageSource messageSource){
        LocalValidatorFactoryBean validatorFactoryBean=new LocalValidatorFactoryBean();
        validatorFactoryBean.setValidationMessageSource(messageSource);
        validatorFactoryBean.setMappingLocations(new ClassPathResource("classpath:i18n/validation"));
        return validatorFactoryBean;
    }


}
